package daos;

import java.util.Date;
import java.util.List;
import java.util.Set;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.hibernate.LockMode;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Expression;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;
import org.springframework.context.ApplicationContext;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;

import pku.ss.movieSystem.common.Constants;
import pku.ss.movieSystem.common.PaginationSupport;
import daos.Movie;

/**
 * A data access object (DAO) providing persistence and search support for Movie
 * entities. Transaction control of the save(), update() and delete() operations
 * can directly support Spring container-managed transactions or they can be
 * augmented to handle user-managed Spring transactions. Each of these methods
 * provides additional information for how to configure it for the desired type
 * of transaction control.
 * 
 * @see daos.Movie
 * @author MyEclipse Persistence Tools
 */

public class MovieDAO extends HibernateDaoSupport {
		
	private static final Log log = LogFactory.getLog(MovieDAO.class);
	
	private UtilsDAO utilsDao;
	
	// property constants
	public static final String MOVIE_ID = "movieId";
	public static final String MOVIE_NAME = "movieName";
	public static final String LANGUAGE = "language";
	public static final String TIME = "time";
	public static final String ZONE = "zone";
	public static final String DIRECTOR = "director";
	public static final String PHOTOGRAPHER = "photographer";
	public static final String SCREEN_WRITER = "screenWriter";
	public static final String DESCRIPTION = "description";
	public static final String POSTER = "poster";

	protected void initDao() {
		// do nothing
	}

	public void save(Movie transientInstance) {
		log.debug("saving Movie instance");
		try {
			getHibernateTemplate().save(transientInstance);
			this.getHibernateTemplate().getSessionFactory().getCurrentSession().beginTransaction().commit();
			log.debug("save successful");
		} catch (RuntimeException re) {
			log.error("save failed", re);
			throw re;
		}
	}

	public void delete(Movie persistentInstance) {
		log.debug("deleting Movie instance");
		try {
			getHibernateTemplate().delete(persistentInstance);
			log.debug("delete successful");
		} catch (RuntimeException re) {
			log.error("delete failed", re);
			throw re;
		}
	}

	public Movie findById(java.lang.Integer id) {
		log.debug("getting Movie instance with id: " + id);
		try {
			Movie instance = (Movie) getHibernateTemplate().get("daos.Movie",
					id);
			return instance;
		} catch (RuntimeException re) {
			log.error("get failed", re);
			throw re;
		}
	}

	public List findByExample(Movie instance) {
		log.debug("finding Movie instance by example");
		try {
			List results = getHibernateTemplate().findByExample(instance);
			log.debug("find by example successful, result size: "
					+ results.size());
			return results;
		} catch (RuntimeException re) {
			log.error("find by example failed", re);
			throw re;
		}
	}

	public List findByProperty(String propertyName, Object value) {
		log.debug("finding Movie instance with property: " + propertyName
				+ ", value: " + value);
		try {
			String queryString = "from Movie as model where model."
					+ propertyName + "= ?";
			return getHibernateTemplate().find(queryString, value);
		} catch (RuntimeException re) {
			log.error("find by property name failed", re);
			throw re;
		}
	}

	public List findByMovieName(Object movieName) {
		return findByProperty(MOVIE_NAME, movieName);
	}

	public List findByLanguage(Object language) {
		return findByProperty(LANGUAGE, language);
	}

	public List findByTime(Object time) {
		return findByProperty(TIME, time);
	}

	public List findByZone(Object zone) {
		return findByProperty(ZONE, zone);
	}

	public List findByDirector(Object director) {
		return findByProperty(DIRECTOR, director);
	}

	public List findByPhotographer(Object photographer) {
		return findByProperty(PHOTOGRAPHER, photographer);
	}

	public List findByScreenWriter(Object screenWriter) {
		return findByProperty(SCREEN_WRITER, screenWriter);
	}

	public List findByDescription(Object description) {
		return findByProperty(DESCRIPTION, description);
	}

	public List findByPoster(Object poster) {
		return findByProperty(POSTER, poster);
	}

	public List findAll() {
		log.debug("finding all Movie instances");
		try {
			String queryString = "from Movie";
			return getHibernateTemplate().find(queryString);
		} catch (RuntimeException re) {
			log.error("find all failed", re);
			throw re;
		}
	}

	public Movie merge(Movie detachedInstance) {
		log.debug("merging Movie instance");
		try {
			Movie result = (Movie) getHibernateTemplate().merge(
					detachedInstance);
			log.debug("merge successful");
			return result;
		} catch (RuntimeException re) {
			log.error("merge failed", re);
			throw re;
		}
	}

	public void attachDirty(Movie instance) {
		log.debug("attaching dirty Movie instance");
		try {
			getHibernateTemplate().saveOrUpdate(instance);
			log.debug("attach successful");
		} catch (RuntimeException re) {
			log.error("attach failed", re);
			throw re;
		}
	}

	public void attachClean(Movie instance) {
		log.debug("attaching clean Movie instance");
		try {
			getHibernateTemplate().lock(instance, LockMode.NONE);
			log.debug("attach successful");
		} catch (RuntimeException re) {
			log.error("attach failed", re);
			throw re;
		}
	}

	public static MovieDAO getFromApplicationContext(ApplicationContext ctx) {
		return (MovieDAO) ctx.getBean("MovieDAO");
	}
	
	/**
	 * find movies by movie name with paging
	 * @author SerenaMing
	 * @param movieName
	 * @param startIndex
	 * @param maxResults
	 * @return
	 */
	public PaginationSupport findMoviesByName(String movieName, int startIndex, int maxResults) {
		
		DetachedCriteria criteria = DetachedCriteria.forClass(Movie.class);
		criteria.add(Expression.like(MOVIE_NAME, "%"+movieName+"%"));
		criteria.addOrder(Order.asc("movieName"));
		if(maxResults == -1) {
			maxResults = Constants.PAGE_SIZE;
		}
		return utilsDao.findPageByCriteria(criteria, maxResults, startIndex, false, Movie.class.getName());
	}
	
	/**
	 * find latest movies with paging
	 * @author SerenaMing
	 * @param movieName
	 * @param startIndex
	 * @param maxResults
	 * @return
	 */
	public PaginationSupport findLatestMovies(int startIndex, int maxResults){
		
		DetachedCriteria criteria = DetachedCriteria.forClass(Movie.class);
		criteria.add(Restrictions.ge("showTime", new Date()));
		criteria.addOrder(Order.desc("showTime"));
		if(maxResults == -1) {
			maxResults = Constants.PAGE_SIZE;
		}
		return utilsDao.findPageByCriteria(criteria, maxResults, startIndex, false, Movie.class.getName());
	}
	/**
	 * find movies by actor name with paging
	 * @author SerenaMing
	 * @param movieName
	 * @param startIndex
	 * @param maxResults
	 * @return
	 */
	public PaginationSupport findMoviesByActorName(String actorName, int startIndex, int maxResults) {
		
		DetachedCriteria movieCriteria = DetachedCriteria.forClass(Movie.class);
		DetachedCriteria enactingCriteria = movieCriteria.createCriteria("enactings");
		DetachedCriteria authorCriteria = enactingCriteria.createCriteria("actor");
		
		authorCriteria.add(Expression.like(ActorDAO.ACTOR_NAME, "%"+actorName+"%"));
		movieCriteria.addOrder(Order.asc("movieName"));
		if(maxResults == -1) {
			maxResults = Constants.PAGE_SIZE;
		}
		return utilsDao.findPageByCriteria(authorCriteria, maxResults, startIndex, true, Movie.class.getName());
	}
	
	/**
	 * find movies by director name with paging
	 * @author SerenaMing
	 * @param movieName
	 * @param startIndex
	 * @param maxResults
	 * @return
	 */
	public PaginationSupport findMoviesByDirectorName(String directorName, int startIndex, int maxResults) {
		
		DetachedCriteria criteria = DetachedCriteria.forClass(Movie.class);
		criteria.add(Expression.like(DIRECTOR, "%"+directorName+"%"));
		criteria.addOrder(Order.asc("movieName"));
		if(maxResults == -1) {
			maxResults = Constants.PAGE_SIZE;
		}
		return utilsDao.findPageByCriteria(criteria, maxResults, startIndex, false, Movie.class.getName());
	}
	
	/**
	 * find all movies with paging
	 * @author SerenaMing
	 * @param movieName
	 * @param startIndex
	 * @param maxResults
	 * @return
	 */
	public PaginationSupport findAllMovie(int startIndex, int maxResults) {
		
		return findMoviesByName("",startIndex, maxResults);
	}

	/**
	 * find all movies with paging
	 * @author SerenaMing
	 * @param movieName
	 * @param startIndex
	 * @param maxResults
	 * @return
	 */
	public PaginationSupport findAllMovies(int startIndex, int maxResults) {
		
		return findMoviesByName("",startIndex, maxResults);
	}

	public void setUtilsDao(UtilsDAO utilsDao) {
		this.utilsDao = utilsDao;
	}
	
	/******************************* added by Sheila *******************************/
	public PaginationSupport findNewlyAddedMovie() {
		DetachedCriteria criteria = DetachedCriteria.forClass(Movie.class);
		criteria.addOrder(Order.desc(MovieDAO.MOVIE_ID));
		
		return utilsDao.findPageByCriteria(criteria, 1, 0, false, Movie.class.getName());
	}
	/******************************* ends Sheila ***********************************/
}